package com.mall.controller;

import com.mall.consts.MallConst;
import com.mall.enums.ResponseEnum;
import com.mall.enums.RoleEnum;
import com.mall.form.UserRegisterForm;
import com.mall.form.UserLoginForm;
import com.mall.pojo.User;
import com.mall.service.IUserService;
import com.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @Author: 黄建
 * @Date: 2020/1/19 22:43
 */
@Slf4j
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 注册
     * @param userForm
     * @return
     */
    @PostMapping("/user/register")
    public ResponseVo register(@Valid @RequestBody UserRegisterForm userForm) {
        log.info("username={}", userForm);


        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        user.setRole(RoleEnum.CUSTOMER.getCode());
        return userService.register(user);
    }

    /**
     * 登录
     * @param userLoginForm
     * @param session
     * @return
     */
    @PostMapping("/user/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userLoginForm, HttpSession session) {
        ResponseVo<User> userResponseVo = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());

        //设置登录状态
        session.setAttribute(MallConst.CURRENT_USER, userResponseVo.getData());

        return userResponseVo;
    }

    /**
     * 获取登录的用户信息
     * @param session
     * @return
     */
    @GetMapping("/user")
    public ResponseVo<User> getUser(HttpSession session) {
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        /*if (user == null) {
            return ResponseVo.error(ResponseEnum.NEED_LOGIN);
        }*/
        return ResponseVo.success(user);
    }

    /**
     * 登出
     * @param session
     * @return
     */
    @PostMapping("/user/logout")
    public ResponseVo<User> logout(HttpSession session) {

        session.removeAttribute(MallConst.CURRENT_USER);

        return ResponseVo.success();
    }

}
